# plugs/test.py
#
#

## gozerlib imports

from gozerlib.utils.exception import exceptionmsg, handle_exception
from gozerlib.tests import tests
from gozerlib.commands import cmnds
from gozerlib.examples import examples
from gozerlib.users import GozerUsers

## basic imports

import time
import random

donot = ['gcalc', ]

def dummy(a, b=None):
    return ""

def handle_testplugs(bot, msg):

    """ test all loaded plugins. """

    if msg.rest:
        match = msg.rest
    else:
        match = ""

    try:
        users = GozerUsers()
        users.add('test', ['test@test',], ['USER', 'OPER'])
    except Exception, ex:
        pass

    bot.channels.setdefault('test', {})

    try:
        loop = int(msg.options['--loop'])
    except (KeyError, ValueError):
        loop = 1

    teller = 0

    for i in range(loop):
        msg.reply('starting loop %s' % str(i))
        examplez = examples.getexamples()
        random.shuffle(examplez)

        for example in examplez:
            if match and match not in example:
                continue

            skip = False

            for dont in donot:
                if dont in example:
                    skip = True

            if skip:
                continue

            teller += 1
            newmessage = copy.deepcopy(msg)
            newmessage.txt = example
            newmessage.onlyqueues = False
            msg.reply('command: ' + example)  
            bot.domsg(newmessage)

            try:
                time.sleep(int(msg.options['--sleep']))
            except (KeyError, ValueError):
                pass

    msg.reply('%s tests run' % teller)

cmnds.add('test-plugs', handle_testplugs, ['OPER', ], options={'--sleep': '0', '--loop': '1'}, threaded=True)
tests.add('test-plugs')

def handle_testsrun(bot, ievent):
    toolate = []
    err = {}

    try:
        loop = ievent.options['--loop']
        loop = int(loop)
    except (KeyError, ValueError):
        loop = 1

    tests.dotests(bot, ievent)
    ievent.reply('%s tests run .. %s errors' % (tests.teller, len(tests.err)))

    if tests.err:
        teller = 0
        for test in tests.err:
            ievent.reply('error #%s %s' % (teller, str(test)))
            teller += 1

    if tests.toolate:
        ievent.reply('toolate: ', tests.toolate, dot=True)

cmnds.add('test-run', handle_testsrun, 'OPER', threaded=True, options={'--loop': '1', '--threaded': 'False'})
#examples.add('test-run', 'run the tests', 'test-run --sleep 0')

def handle_forcedexception(bot, ievent):
    raise Exception('test exception')

cmnds.add('test-forcedexception', handle_forcedexception, 'OPER')
tests.add('test-forcedexception')

def handle_testhammer(bot, msg):
    if msg.rest:
        match = msg.rest
    else:
        match = ""

    try:
        users.add('test', ['test@test',], ['USER', 'OPER'])
    except Exception, ex:
        pass

    bot.channels.setdefault('test', {})

    try:
        loop = int(msg.options['--loop'])
    except (KeyError, ValueError):
        loop = 1

    try:
        hammer = int(msg.options['--hammer'])
    except (KeyError, ValueError):
        hammer = 10

    teller = 0

    for i in range(loop):
        msg.reply('starting loop %s' % str(i))
        examplez = examples.getexamples()
        random.shuffle(examplez)

        for example in examplez:

            if match and match not in example:
                continue

            skip = False

            for dont in donot:
                if dont in example:
                    skip = True

            if skip:
                continue

            teller += 1

            newmessage = cpy(msg)
            newmessage.txt = example
            newmessage.onlyqueues = False
            msg.reply('command: ' + example)  
            for hammernr in range(hammer):
                try:
                    bot.domsg(newmessage)
                except Exception, ex:
                    handle_exception()

            try:
                time.sleep(int(msg.options['--sleep']))
            except (KeyError, ValueError):
                pass

    msg.reply('%s tests run' % teller)

cmnds.add('test-hammer', handle_testhammer, 'OPER')
cmnds.add('test-hammer', handle_testhammer, 'OPER', threaded=True)
#examples.add('test-hammer', 'run the hammer tests', 'test-hammer')
#tests.add('test-hammer')

#def handle_tojson(bot, ievent):
#    ievent.reply(ievent.tojson())
#
#cmnds.add('test-json', handle_tojson, 'OPER')

def handle_testsay(bot,ievent):
    #ievent.reply("using %s" % ievent.channel)
    bot.say(ievent.channel, 'yoooo!')

cmnds.add('test-say', handle_testsay, 'OPER')

def handle_testtoppost(bot,ievent):
    #ievent.reply("using %s" % ievent.channel)
    bot.toppost(ievent.channel, 'yoooo!')

cmnds.add('test-toppost', handle_testtoppost, 'OPER')

def handle_testsayroot(bot,ievent):
    #ievent.reply("using %s" % ievent.channel)
    bot.sayroot(ievent.channel, 'yoooo!')

cmnds.add('test-sayroot', handle_testsayroot, 'OPER')
